package com.test.rest.service;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;

import com.test.rest.bean.Category;
import com.test.rest.dao.CategoryDao;

@Path("/categoryservice")
@Produces({"application/xml","application/json"})
public class CategoryService {
	
	private CategoryDao categoryDao;

	public CategoryDao getCategoryDao() {
		return categoryDao;
	}

	public void setCategoryDao(CategoryDao categoryDao) {
		this.categoryDao = categoryDao;
	}

	@GET
	@Path("/category/{id}")
	public Category getCategory(@PathParam("id") String id) {
		Category cat = categoryDao.getCategory(id);
		
		if (null == cat) {
			
			ResponseBuilder builder = Response.status(Status.BAD_REQUEST);
			builder.type("applicaton/xml");
			builder.entity("<error>Category not found.</error>");
			
			throw new WebApplicationException(builder.build());
			
		} else {
			return cat;
		}
	}

	@GET
	@Path("/category/{id}/books")
	public Response getBooks(@PathParam("id") String id) {
		
		Category cat = categoryDao.getCategory(id);
		
		
		if (null == cat) {
			
			return Response.status(Status.NOT_FOUND).build();
			
		} else {
			
			cat.setBooks(categoryDao.getBooks(id));
			
			return Response.ok(cat).build();
		}
		
	}
	
	@POST
	@Path("/category")
	public Response addCategory(Category category) {
		Category cat = categoryDao.getCategory(category.getCategoryId());
		
		if(null != cat) {
			return Response.status(Status.BAD_REQUEST).build();
		} else {
			categoryDao.addCategory(category);
			return Response.ok(category).build();
		}
		
	}
	
}
